package com.example.gongzhong1.utils;
import net.sf.json.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;

/**
* @Description:
* @Author:         xiayuxuanmin
* @CreateDate:     2019/6/4 15:10
* @Version:        1.0
*/
public class WeixinUtil {
    public static final String APPID = "wx0670fc36426cc800";
    public static final String APPSECRET = "a2e7d57f66bdbbc81f89b70ee8537bc3";

    //获取access_token的接口地址(GET) 限200次/天
    public static final
        String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    //菜单创建POST 限100次/天
    public static
        String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";

    /**
     * 发送https请求
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outputStr 提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            //SSLSocket扩展Socket并提供使用SSL或TLS协议的安全套接字。这种套接字是正常的流套接字，但是它们在基础网络传输协议(如TCP)上添加了安全保护层。
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            // 创建URL对象
            URL url = new URL(requestUrl);
            // 创建HttpsURLConnection对象，并设置其SSLSocketFactory对象
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);

            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type","application/json;charset=utf-8");
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            conn.setRequestMethod(requestMethod);

            if("GET".equalsIgnoreCase(requestMethod)){
                conn.connect();
            }

            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 取得该连接的输入流，以读取响应内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            // 读取服务器的响应内容并显示
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }

            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            System.out.println("Weixin servet 连接超时");
        } catch (Exception e) {
            System.out.println("https 请求失败,error:{}");
        }
        return jsonObject;
    }

    public static AccessToken getAccessToken(String appid,String appsecret){
        AccessToken accessToken = null;
        String requestUrl = access_token_url.replace("APPID",appid).replace("APPSECRET",appsecret);
        JSONObject jsonObject = httpsRequest(requestUrl,"GET",null);

        //如果请求成功
        if (null != jsonObject) {
            try {
                accessToken = new AccessToken();
                accessToken.setToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
            }catch (Exception e){
                accessToken = null;
                //获取token失败
                System.out.println("获取token失败,errcode:"+jsonObject.getInt("errcode")+",errmsg:"+jsonObject.getString("errmsg"));
            }
        }
        return accessToken;
    }

    /**
     *  @Description 
     *  @Param [menu, accessToken]
     *  @Return int
     *  @Author xiayuxuanmin
     *  @Date 2019/4/27
     */
    public static int createMenu(Menu menu,String accessToken){
        int result = 0;
        //拼接创建菜单的URL
        String url = menu_create_url.replace("ACCESS_TOKEN",accessToken);
        //将菜单对象转化为JOSN字符串
        String jsonMenu = JSONObject.fromObject(menu).toString();
        System.out.println("发送的数据"+jsonMenu);
        //调用接口创建菜单
        JSONObject jsonObject = httpsRequest(url,"POST",jsonMenu);
        if (null != jsonObject) {
            if (0 != jsonObject.getInt("errcode")) {
                result = jsonObject.getInt("errcode");
                System.out.println("创建菜单失败,errcode:"+result+",errmsg:"+jsonObject.getString("errmsg"));
            }
        }
        return result;
    }
}
